package cn.edu.zafu.bigdata.YinMingyan.chapter11;

import java.io.*;
import java.net.*;

// 简单的TCP聊天服务器
public class TCPChatServer {
    public static void main(String[] args) {
        int port = 5678; // 服务器监听的端口号
        try (ServerSocket serverSocket = new ServerSocket(port)) {
            System.out.println("TCP Server is listening on port " + port);

            while (true) {
                try {
                    // 等待客户端连接
                    Socket clientSocket = serverSocket.accept();
                    System.out.println("TCP Client connected.");

                    // 获取输入输出流
                    BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                    PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);

                    // 读取客户端发送的消息并回复
                    String inputLine;
                    while ((inputLine = in.readLine()) != null) {
                        System.out.println("TCP Client says: " + inputLine);
                        out.println("TCP Server回复: " + inputLine); // 回显客户端消息
                    }
                } catch (IOException e) {
                    System.out.println("Error handling client: " + e.getMessage());
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            System.out.println("Server exception: " + e.getMessage());
            e.printStackTrace();
        }
    }
}